﻿using FastCloud.Base.Attribute;
using FastCloud.Base.Config;
using FastUtil.Log;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastCloud.Base.Filter
{
    [CloudFilter(SoryNum = 99)]
    public class GlobalExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            string FloderPath = CloudUtil.GetContentPath() + "/Logs";
            DirectoryInfo SystemLogDir = new DirectoryInfo(FloderPath);
            if (!SystemLogDir.Exists)
            {
                SystemLogDir.Create();
            }
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("异常请求url:{0}", context.HttpContext.Request.Path + Environment.NewLine);
            builder.AppendFormat("异常信息:{0}", context.Exception.Message + Environment.NewLine);
            builder.AppendFormat("堆栈信息:{0}", context.Exception.StackTrace + Environment.NewLine);
            LogUtil.WriteLog(CloudUtil.GetContentPath() + "/Logs/Exception", "log_", builder.ToString());
            bool IsAjaxCall = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
            if (IsAjaxCall)
            {
                context.Result = Result.Error("系统发生错误，请联系管理员！");
                context.ExceptionHandled = true;
            }
            else
            {
                context.Result = new RedirectResult(CloudUtil.GetRootPath() + "frame/home/error/500");
                context.ExceptionHandled = true;
            }

        }
    }
}
